package servlet;

import pojo.Categories;
import pojo.Food;
import pojo.Merchant;
import pojo.PageBean;
import service.CategoriesManager;
import service.FoodsManager;
import service.factory.ManagerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ShowFoodListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private FoodsManager foodsManager;
	private CategoriesManager categoriesManager;
	
    public ShowFoodListServlet() {
        super();
        foodsManager = ManagerFactory.getFoodsManagerInstance();
        categoriesManager = ManagerFactory.getCategoriesManagerInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("showfood");
		request.setCharacterEncoding("UTF-8");
		String curr = request.getParameter("curr");
		if(curr == null){
		 curr="1";
		}
		int current = Integer.parseInt(curr);
		int pageSize = (int)this.getServletContext().getAttribute("pageSize");
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant) session.getAttribute("user");
		String mId = merchant.getId();
		List<Food> foodList = new ArrayList<Food>();
		int count = 0;
		List<Categories> categoriesList = categoriesManager.findAll();
		String typeId = request.getParameter("typeId") == null ? "all" : request.getParameter("typeId");
		if("all".equals(typeId)){
			foodList = foodsManager.findAllByMerchant(mId, current, pageSize);
			request.setAttribute("typeId", "all");
			count = foodsManager.getCountByMerchant(mId);
		}else{
			foodList = foodsManager.findFoodByCategory(mId, typeId, current, pageSize);
			request.setAttribute("typeId", typeId);
			count = foodsManager.getCountByCategory(mId, typeId);
		}
		PageBean<Food> pageBean = new PageBean<>(current, pageSize, foodList, count);
		request.setAttribute("categoriesList", categoriesList);
	//	request.setAttribute("foodList", foodList);
		request.setAttribute("pageBean", pageBean);
		request.getRequestDispatcher("/WEB-INF/sec/control/foodList.jsp").forward(request, response);
	}
}
